package private

import (
	"errors"
	"html"
	"qianggougo/controller/common"
	"qianggougo/model"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

/**
 * 微信授权获取个人信息
 */
func WxAccredit(c *gin.Context) {
	// 1. 定义接收结构体
	type Request struct {
		NickName  string `json:"nickName"`
		AvatarUrl string `json:"avatarUrl"`
		Userid    int    `json:"userid"`
	}

	// 2. 解析JSON
	var req Request
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(400, gin.H{"error": "参数解析失败"})
		return
	}

	nickName := html.EscapeString(req.NickName)
	avatarUrl := req.AvatarUrl
	userid := req.Userid

	if nickName == "" || avatarUrl == "" || userid == 0 {
		c.JSON(200, gin.H{"err": 1, "msg": "授权失败，参数错误"})
		return
	}

	if len(nickName) > 50 || len(avatarUrl) > 255 {
		c.JSON(200, gin.H{"err": 1, "msg": "授权失败，参数长度超过限制"})
		return
	}

	var user model.User
	userInfo := common.DB.Where("id = ?", userid).First(&user)
	if userInfo.Error == nil {
		common.DB.Model(&user).Updates(model.User{
			WxNickname: nickName,
			WxAvatar:   avatarUrl,
		})
	}
	c.JSON(200, gin.H{"err": 0, "msg": "授权成功"})
}

/**
 * 选择阵容
 */
func SelectTheLineup(c *gin.Context) {
	// 1. 定义接收结构体
	type Request struct {
		Lineup int `json:"lineup"`
	}

	// 2. 解析JSON
	var req Request
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(400, gin.H{"error": "参数解析失败", "details": err.Error()})
		return
	}

	Lineup := req.Lineup
	userid := c.MustGet("userid").(int) // 类型断言

	var user model.User
	result := common.DB.Model(&user).Where("id = ?", userid).Update("lineup", Lineup)
	if result.Error != nil {
		if errors.Is(result.Error, gorm.ErrRecordNotFound) {
			c.AbortWithStatusJSON(401, gin.H{"err": 1, "msg": "找不到token"})
		} else {
			c.AbortWithStatusJSON(500, gin.H{"err": 2, "msg": "查询有误"})
		}
		return
	}
	c.JSON(200, gin.H{"err": 0, "msg": "选择成功"})
}

/**
 * 获取得分
 */
func GetScore(c *gin.Context) {
	var total model.Total
	totalInfo := common.DB.Take(&total)
	if totalInfo.Error == nil {
		c.JSON(200, gin.H{"err": 0, "msg": "获取成功", "redscore": total.RedScore, "bluescore": total.BlueScore})
		return
	}
	c.AbortWithStatusJSON(500, gin.H{"err": 1, "msg": "查询有误"})
}
